#!env python
#coding=utf-8

import os
import sys

def imageNameGet(verFilePathName):
    with open(verFilePathName, "r") as f:
        for line in f:
            if "VERSION_MODEL" in line:
                verModel = line.replace('\n', '').split()[-1].split('\"')[1]
            elif "VERSION_DATE_YEAR" in line:
                verDateYear = line.replace('\n', '').split()[-1]
            elif "VERSION_DATE_MONTH" in line:
                verDateMonth = line.replace('\n', '').split()[-1]
            elif "VERSION_DATE_DAY" in line:
                verDateDay = line.replace('\n', '').split()[-1]
            elif "VERSION_HARDWARE" in line:
                verHardware = line.replace('\n', '').split()[-1]
            elif "VERSION_MAJOR" in line:
                verMajor = line.replace('\n', '').split()[-1]
            elif "VERSION_MINOR" in line:
                verMinor = line.replace('\n', '').split()[-1]
        imageName = "{0}-{1}-{2}-{3}-S{4}.{5}.{6}".format(verModel, verDateYear, verDateMonth, verDateDay, verHardware, verMajor, verMinor)
    return verModel, imageName

def imageMerge(bootPathName, appPathName, imagePathName):
    boot = open(bootPathName, "r")
    app = open(appPathName, "r")
    image = open(imagePathName, "w")
    try:
        for line in boot.readlines():
            if ":00000001FF" in line:
                break
            image.write(line)
        image.write(app.read())
    except Exception as e:
        print(e)
    finally:
        boot.close()
        app.close()
        image.close()

if __name__ == "__main__":
    for i in range(len(sys.argv) - 1):
        if sys.argv[i] == "-b" or sys.argv[i] == "--board":
            board = sys.argv[i + 1]
    projectSourcePath = sys.path[0] + "\\..\\.."
    verSourcePathName = projectSourcePath + "\\boards\\" + board + "\\config\\version.h"
    bootPathName = projectSourcePath + "\\boards\\" + board + "\\.mdk\\bootloader.hex"
    prodectName, imageName = imageNameGet(verSourcePathName)
    binSourcePath = projectSourcePath + "\\boards\\" + board + "\\.mdk\\bin"
    hexSourcePathName = projectSourcePath + "\\boards\\" + board + "\\.mdk\\output\\" + prodectName + ".hex"
    imagePathName = binSourcePath + "\\" + imageName + ".hex"
    # check bin source dir if exits
    if os.path.exists(binSourcePath) != True:
        os.makedirs(binSourcePath)
    imageMerge(bootPathName, hexSourcePathName, imagePathName)